package com.roncoo.education.constants;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.roncoo.education.util.tools.IdWorker;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

public final class UploadUtil {


	public static String uploadFileByLocal(MultipartFile multipartFile) throws IOException {
		//abcdefg.pdf
		String fileFullName = multipartFile.getOriginalFilename();
		//.pdf
		String fileSuffix = fileFullName.substring(fileFullName.lastIndexOf("."), fileFullName.length());
		// abcdefg
		String fileSimpleName = fileFullName.substring(0, fileFullName.lastIndexOf("."));
		//重新生成文件名
		Long HashDigest = IdWorker.getId();
		String fileHashDigestFullName = HashDigest + fileSuffix;
		//先存储到本地 然后异步推送到 云端
		File targetFile = new File(CourseConstants.UPLOAD_WINDOWS_PATH + fileHashDigestFullName);
		// 判断文件目录是否存在，不存在就创建文件目录
		if (!targetFile.getParentFile().exists()) {
			targetFile.getParentFile().mkdirs();
		}
		multipartFile.transferTo(targetFile);
//		String resourcePath = "http://127.0.0.1:5710/upload/" + fileHashDigestFullName;
		String resourcePath = CourseConstants.UPLOAD_RESOURCE_URL + fileHashDigestFullName;
		return resourcePath;
	}


	public static String uploadFileByOSS(MultipartFile multipartFile) {
		OSSClient ossClient = new OSSClient(CourseConstants.endpoint, CourseConstants.accessKeyId, CourseConstants.accessKeySecret);
//缓存文件上传至OSS
		//abcdefg.pdf
		String fileFullName = multipartFile.getOriginalFilename();
		//.pdf
		String fileSuffix = fileFullName.substring(fileFullName.lastIndexOf("."), fileFullName.length());
		// abcdefg
		String fileSimpleName = fileFullName.substring(0, fileFullName.lastIndexOf("."));
		//重新生成文件名
		Long HashDigest = IdWorker.getId();
		String fileHashDigestFullName = HashDigest + fileSuffix;
		String fileFolderPath="upload/";
		try {
			PutObjectResult putObjectResult = ossClient.putObject(CourseConstants.bucketName, fileFolderPath+fileHashDigestFullName, multipartFile.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
		//System.out.println("\t\n=AAAAAAAA==============\t\n"+JSON.toJSONString(putObjectResult));
		//关闭OSS实例
		ossClient.shutdown();

		String resultPath = "http://gudian-integration.oss-cn-beijing.aliyuncs.com/upload/"+fileHashDigestFullName;
		//云存储返回的路径
		// public static final String url = "http://gudian-integration.oss-cn-beijing.aliyuncs.com";
		//http://gudian-integration.oss-cn-beijing.aliyuncs.com/1279823409296330753.png
		return resultPath;
	}

}
